const express = require('express')
const fs = require('fs')
const config = require(process.cwd() + '/src/config/config')
const fileUtils = require(process.cwd() + '/src/utils/file')
const Game = require(process.cwd() + '/src/class/index')
const MapSetting = require(process.cwd() + '/src/utils/map')

let router = express.Router()

// 导出所有配置文件
const doAction = async (req) => {
  // 先删除output文件夹,重建新的
  const outputPath = config.outputPath
  await fileUtils.deleteDir(outputPath)
  await fileUtils.createFolder(outputPath)
  
  // 创建总的配置文件
  const settingName = 'settings.json'
  const settingPath = config.outputPath + settingName
  let settings = {}
  
  // 再导出所有资源
  await outputResources()
  
  // 导出地图文件
  await outputMap(settings)
  
  // 保存总配置文件
  const buffer = JSON.stringify(settings)
  await fs.promises.writeFile(settingPath, buffer)
}

// 导出所有资源
const outputResources = async () => {
  // 拷贝Autotile
  await fileUtils.copyDir(config.autotilesPath, config.outputPath)
  // 拷贝images
  await fileUtils.copyDir(config.imagesPath, config.outputPath)
  // 拷贝全景图片
}

const outputMap = async (settings) => {
  // 获取所有地图文件
  let tempMap = new Game.Map()
  let maps = await tempMap.getAllMaps()
  // 在配置文件中记录所有地图
  settings.maps = maps
  // 输出具体的文件
  const len = maps.length
  for (let i = 0; i < len; i++) {
    let map = new Game.Map()
    await map.init(maps[i])
    await map.output()
  }
}

/* GET users listing. */
router.post('/', function (req, res) {
  doAction(req).then(() => {
    res.sendStatus(200)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

module.exports = router
